﻿using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Drawing;
using Techstar.Dialog;
using Techstar.Utils;
using SmartMD.Manager;
using SmartMD.DataModel;

namespace SmartMD.Manager
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private void AppStartingUp(object sender, StartupEventArgs e)
        {
            Org.HessianSystem.IgnoreNamespace = true;
            bool splash = true;
            bool debug = false;
            var group = "";
            if (e != null && e.Args != null && e.Args.Length > 0)
            {
                foreach (var arg in e.Args)
                {
                    var str = arg.ToLower();
                    if (str.IndexOf("connect:") == 0)
                    {
                        var strs = arg.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                        if (strs.Length == 2)
                        {
                            group = strs[1];
                        }
                    }
                    if (str == "-hidesplash")
                        splash = false;
                    else if (str == "-debug")
                        debug = true;
                }
            }

            if (!string.IsNullOrEmpty(group))
            {
                var allprocess = System.Diagnostics.Process.GetProcesses();
                foreach (var process in allprocess)
                {
                    try
                    {
                        if (process.Id == Process.GetCurrentProcess().Id)
                        {
                            continue;
                        }
                        var fileName1 = process.MainModule.FileName;
                        if (string.IsNullOrEmpty(fileName1)) continue;
                        if (fileName1.ToLower() == System.Windows.Forms.Application.ExecutablePath.ToLower())
                        {
                            process.Kill();
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }


            if (debug)
                NativeMethods.AllocConsole();

            this.DispatcherUnhandledException += Techstar.Windows.ExceptionBox.ShowErrorBox;

            Org.HessianSystem.Register(typeof(MainWindow).Assembly);
            var mainform = new MainWindow();

            Techstar.Windows.SplashScreen.CurrentSplash = new Techstar.Windows.SplashScreen();

            var fileName = Path.ChangeExtension(System.Windows.Forms.Application.ExecutablePath, ".png");
            Bitmap bitmap = File.Exists(fileName) ? new Bitmap(fileName) : new Bitmap(typeof(MainWindow), "Images.splash.png");
            Techstar.Windows.SplashScreen.CurrentSplash.DefaultImage = bitmap;

            Techstar.Windows.SplashScreen.CurrentSplash.PrepareDiagramImage("");

            if (splash)
                Techstar.Windows.SplashScreen.CurrentSplash.Show();

            if (string.IsNullOrEmpty(group))
            {
                Techstar.Windows.SplashScreen.CurrentSplash.Message = "正在检测更新...";
               /* if (SVNUpdate.Svn.CheckUpdate("标本管理平台", SingletonManager.AppPath))
                {
                    return;
                }*/

                
            }
            
            Techstar.Windows.SplashScreen.CurrentSplash.Message = "启动程序...";

            Techstar.Windows.SplashScreen.CurrentSplash.Message = "正在注册数据实体...";

            Org.HessianSystem.Register(typeof(ConnectConfig).Assembly);
            Org.HessianSystem.Register(typeof(EntityBase).Assembly);

            Techstar.Windows.SplashScreen.CurrentSplash.Message = "正在加载插件...";
            LoadPlugins();

            Techstar.Windows.SplashScreen.CurrentSplash.Message = "正在加载主窗体...";
            mainform.Init();
            mainform.Loaded += MainFormLoad;
            mainform.Show();
            new WindowLogin { Owner = mainform }.ShowDialog();
        }

        private static void MainFormLoad(object sender, EventArgs e)
        {
            Techstar.Windows.SplashScreen.CurrentSplash.Close();
            Manager.MainWindow.Instance.Loaded -= MainFormLoad;
        }

        private static void LoadPlugins()
        {
            var path = System.IO.Path.Combine(SingletonManager.AppPath, "Plugins");
            string[] files = Directory.GetFiles(path, "*.Plugins.dll");
            foreach (string file in files)
            {
                try
                {
                    var assembly = Assembly.LoadFrom(file);
                    Org.HessianSystem.Register(assembly);
                   // CanvasEx.RegisterControl(assembly);
                }
                catch (Exception exception1)
                {
                    TaskDialogEx.Error(exception1.Message);
                }
            }
        }
    }
}
